<?php

namespace App\Repository;

use App\Entity\Money;
use App\Entity\MoneyLog;
use App\Entity\MoneyType;
use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Common\Persistence\ManagerRegistry;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Repository\DocumentRepository;

/**
 * @method Money|null find($id, $lockMode = null, $lockVersion = null)
 * @method Money|null findOneBy(array $criteria, array $orderBy = null)
 * @method Money[]    findAll()
 * @method Money[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class MoneyRepository extends DocumentRepository
{
    public function __construct(DocumentManager $dm)
    {
        parent::__construct($dm, $dm->getUnitOfWork(),$dm->getClassMetadata(Money::class));
    }

    public function getUserMoneyByType(User $user,MoneyType $moneyType)
    {
        $money = $this->findOneBy(array("user"=>$user,"type"=>$moneyType));
        if (!$money) {
            $money = new Money();
            $money->setUser($user)
                ->setType($moneyType)
                ->setMoney(0);
            $this->dm->persist($money);
            $this->dm->flush();
        }
        return $money;
    }
}
